package com.shycloud.mido.homework.sharding;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.shycloud.mido.common.util.consistenthash.ConsistentHash;
import com.shycloud.mido.common.util.consistenthash.HashFunction;

/**
 * @author Xiaoxing Yu
 * @date 2020/11/18 下午8:06
 **/
@Component
public class ConsistentHashSharding {

	public static ConsistentHash<Integer> ipHash = null;

	private ConsistentHash<Integer> instance;

	public ConsistentHash<Integer> getInstance() {
		return instance;
	}

	@PostConstruct
	public void init() {
		Set<Integer> nodes = new HashSet<Integer>();
		for (int i = 0; i < 100; i++) {
			nodes.add(i);
		}

		ipHash = new ConsistentHash<Integer>(new HashFunction(), 50, nodes);
		System.out.println("init hash circle in PostConstruct");
	}

	static {
		Set<Integer> nodes = new HashSet<Integer>();
		for (int i = 0; i < 100; i++) {
			nodes.add(i);
		}

		ipHash = new ConsistentHash<Integer>(new HashFunction(), 50, nodes);
		System.out.println("init hash circle in static");
	}

	public ConsistentHashSharding () {
		Set<Integer> nodes = new HashSet<Integer>();
		for (int i = 0; i < 100; i++) {
			nodes.add(i);
		}

		instance = new ConsistentHash<Integer>(new HashFunction(), 50, nodes);
//		System.out.println("init hash circle in construct");
	}

	public static Integer getConsistentHash(Object key) {
		return ipHash.get(key);
	}

	public Integer getConsistHash(Object key) {
		return instance.get(key);
	}

}
